package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import com.example.geoaimavlink_android.R
import com.geoai.module.common.thread.ExecutorsManager
import kotlinx.android.synthetic.main.frag_motor_test.btn_motor1
import kotlinx.android.synthetic.main.frag_motor_test.btn_motor2
import kotlinx.android.synthetic.main.frag_motor_test.btn_motor3
import kotlinx.android.synthetic.main.frag_motor_test.btn_motor4
import kotlinx.android.synthetic.main.frag_motor_test.btn_motor_all
import kotlinx.android.synthetic.main.frag_motor_test.btn_stop
import kotlinx.android.synthetic.main.frag_motor_test.edt_times
import kotlinx.android.synthetic.main.frag_motor_test.seekbar
import kotlinx.android.synthetic.main.frag_motor_test.tv_progress
import java.util.concurrent.ScheduledFuture

class MotorTestFragment: BaseFragment() {

    private var mCurrentProgress = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_motor_test, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        seekbar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener{
            override fun onProgressChanged(
                seekBar: SeekBar?,
                progress: Int,
                fromUser: Boolean
            ) {
                requireActivity().runOnUiThread { tv_progress?.text = "$progress %" }
                mCurrentProgress = progress
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })
        btn_stop.setOnClickListener {
            cancelThread()
        }
        btn_motor1.setOnClickListener {
            edt_times?.text?.toString()?.toIntOrNull().let {
                enableMotorControl(1, mCurrentProgress, it)
            }
        }
        btn_motor2.setOnClickListener {
            edt_times?.text?.toString()?.toIntOrNull().let {
                enableMotorControl(2, mCurrentProgress, it)
            }
        }
        btn_motor3.setOnClickListener {
            edt_times?.text?.toString()?.toIntOrNull().let {
                enableMotorControl(3, mCurrentProgress, it)
            }
        }
        btn_motor4.setOnClickListener {
            edt_times?.text?.toString()?.toIntOrNull().let {
                enableMotorControl(4, mCurrentProgress, it)
            }
        }
        btn_motor_all.setOnClickListener {
            edt_times?.text?.toString()?.toIntOrNull().let {
                enableMotorControl(-1, mCurrentProgress, it)
            }
        }
    }

    private var executeAtFixedRate: ScheduledFuture<*>? = null

    private var enablePersistentTimes = -1L

    private fun enableMotorControl(index: Int, outputPercent: Int, persistentTimes: Int?) {
        if (persistentTimes == null || persistentTimes < 0) {
            // 仅触发一次
            extracted(index, outputPercent)
        } else if (executeAtFixedRate == null) {
            enablePersistentTimes = System.currentTimeMillis()

            executeAtFixedRate = ExecutorsManager.get().executeAtFixedRate({
                if (System.currentTimeMillis() - enablePersistentTimes > persistentTimes * 1000) {
                    cancelThread()
                    return@executeAtFixedRate
                }

                requireActivity().runOnUiThread {
                    edt_times?.isEnabled = false
                    btn_motor1?.isEnabled = false
                    btn_motor2?.isEnabled = false
                    btn_motor3?.isEnabled = false
                    btn_motor4?.isEnabled = false
                    btn_motor_all?.isEnabled = false
                }

                extracted(index, outputPercent)
            }, 1000, 1000)
        } else {
            cancelThread()
        }
    }

    private fun cancelThread() {
        executeAtFixedRate?.cancel(true)
        executeAtFixedRate = null
        enablePersistentTimes = -1L
        requireActivity().runOnUiThread {
            edt_times?.isEnabled = true
            btn_motor1?.isEnabled = true
            btn_motor2?.isEnabled = true
            btn_motor3?.isEnabled = true
            btn_motor4?.isEnabled = true
            btn_motor_all?.isEnabled = true
        }
    }

    private fun extracted(index: Int, outputPercent: Int) {
        if (index > 0) {
            getProduct()?.flyControllerManager?.setMotorTestCommand(index, outputPercent) {
                showToast(it?.description ?: "success")
            } ?: showToast("flyControllerManager is null")
        } else {
            //全部触发
            getProduct()?.flyControllerManager?.setMotorTestCommand(1, outputPercent, null)
            getProduct()?.flyControllerManager?.setMotorTestCommand(2, outputPercent, null)
            getProduct()?.flyControllerManager?.setMotorTestCommand(3, outputPercent, null)
            getProduct()?.flyControllerManager?.setMotorTestCommand(4, outputPercent, null)
        }
    }
}